//
//  HearingChapterDetailViewController.m
//  Learn
//
//  Created by 迟建国 on 2024/4/3.
//  Copyright © 2024 迟建国. All rights reserved.
//

#import "HearingChapterDetailViewController.h"
#import "HearingQuestionTableViewCell.h"
#import "HearingOptionTableViewCell.h"
#import "QuestionTurnkCell.h"
#import <AVFoundation/AVFoundation.h>
#import "HomeRequest.h"
#import "TextbookQuestionsModel.h"
#import "PlayManager.h"
#import "ChangeItemView.h"
#import "TingliResultViewController.h"
#import "QuestionStateView.h"
#import "QuestionWriteTableViewCell.h"

typedef enum : NSUInteger {
    QuestionStateReady, // 初始化
    QuestionStateTingtigan, // 读大题题干，只显示题干
    QuestionStateYueti,     // 阅读时间，题干置灰，显示问题及选项 ，
    QuestionStateDuNeirong, // 读取题内容，题干置灰，显示问题及选项 ，读题loading下一步，倒计时
    QuestionStateStartDati, // 开始答题，答题时间，答题loading，下一步，倒计时
    QuestionStateEndDati,   // 结束答题，
} QuestionState;
// 答题流程：0 1 2 3 4 5 -> 2 3 4 5 -> 2 3 4 5

@interface HearingChapterDetailViewController ()<UITableViewDelegate, UITableViewDataSource,PlayManagerDelegate>


@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) QuestionStateView *stateView;

@property (nonatomic, strong) TextbookQuestionsModel *testModel; // 测试卷子
@property (nonatomic, strong) NSArray *dataAry; // 大题列表

@property (nonatomic, assign) NSUInteger mainIndex; // 大题index
@property (nonatomic, assign) NSUInteger subIndex;  // 小题index
@property (nonatomic, assign) NSUInteger childrenIndex;  // children题index

@property (nonatomic, assign) QuestionState questionState;  // 问题当前状态

@property (nonatomic, strong) PlayManager *player;

@property (nonatomic, strong) NSTimer *timer;

@end

@implementation HearingChapterDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = rgba(245, 245, 245, 1);
    
    self.player = [PlayManager sharPlayManager];
    self.player.delegate = self;
    
    [self setUI];
    [self setNavUI];
    [self loadData];
    
}

- (void)setNavUI {
    UIView *nav = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, NavigationBarHeight)];
    nav.backgroundColor = rgba(245, 245, 245, 1);
    [self.view addSubview:nav];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:[UIImage imageNamed:@"icon_back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [nav addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(nav.mas_left).offset(5);
        make.bottom.equalTo(nav.mas_bottom);
        make.width.offset(50);
        make.height.offset(44);
    }];
    
    UILabel *titleL = [[UILabel alloc] init];
    titleL.text = self.model.resourceName;
    titleL.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:16];
    titleL.textColor = rgb(51, 51, 51);
    titleL.textAlignment = NSTextAlignmentCenter;
    [nav addSubview:titleL];
    [titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(nav.mas_bottom);
        make.centerX.equalTo(nav.mas_centerX);
        make.height.offset(44);
    }];
    
    UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [saveBtn setImage:[UIImage imageNamed:@"icon_save"] forState:UIControlStateNormal];
    [saveBtn addTarget:self action:@selector(rightBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [nav addSubview:saveBtn];
    [saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right).offset(-10);
        make.bottom.equalTo(nav.mas_bottom);
        make.height.offset(44);
    }];
    
}

- (void)setUI {
    UIView *testView = [[UIView alloc] init];
    testView.backgroundColor = [UIColor whiteColor];
    testView.layer.cornerRadius = 15;
    testView.layer.masksToBounds = YES;
    [self.view addSubview:testView];
    [testView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(10);
        make.top.equalTo(self.view.mas_top).offset(10 + NavigationBarHeight);
        make.right.equalTo(self.view.mas_right).offset(-10);
        make.bottom.equalTo(self.view.mas_bottom).offset(-SafeAreaBottomHeight - 130);
    }];
    
    self.tableView=[[UITableView alloc]initWithFrame:CGRectMake(0,0, SCREEN_W - 20, SCREEN_H - NavigationBarHeight - SafeAreaBottomHeight - 130) style:UITableViewStylePlain];
    [testView addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.bottom.equalTo(testView);
    }];
    if (@available(iOS 13.0, *)) {
        [self.tableView setAutomaticallyAdjustsScrollIndicatorInsets:NO];
    }
    
    if (@available(iOS 15.0, *)) {
        self.tableView.sectionHeaderTopPadding = 0;
    }
    
    self.tableView.backgroundColor=[UIColor whiteColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 60;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    [self.tableView registerNib:[UINib nibWithNibName:@"HearingQuestionTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"HearingQuestionTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"HearingOptionTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"HearingOptionTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"QuestionTurnkCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"QuestionTurnkCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"QuestionWriteTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"QuestionWriteTableViewCell"];
   
    WS(WeakSelf)
    self.stateView = [[QuestionStateView alloc] init];
    self.stateView.nextBlock = ^{
        [WeakSelf nextAction];
    };
    [self.view addSubview:self.stateView];
    [self.stateView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view).offset(0.0);
        make.bottom.equalTo(self.view).offset(-10);
        make.top.equalTo(testView.mas_bottom).offset(10);
    }];
    
}

- (void)loadData {
    [self showLoadingViewWithText:nil];
    [HomeRequest getTextbookTestQuestionsWithId:self.model.versionId type: @"听力" result:^(TextbookQuestionsModel *model) {
        [self removeLoadingView];
        self.testModel = model;
        self.dataAry = model.resource.items;
        self.mainIndex = 0;
        self.subIndex = 0;
        self.childrenIndex = 0;
        self.questionState = QuestionStateReady;
        [self.tableView reloadData];
    }];
    
}

- (void)startTimerWithTime:(NSUInteger)time {
    [self stopTimer];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        self.timer = [NSTimer scheduledTimerWithTimeInterval:time target:self selector:@selector(timerFired:) userInfo:nil repeats:NO];
        // 将定时器添加到当前线程的 RunLoop 中
        [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
        // 启动 RunLoop
        [[NSRunLoop currentRunLoop] run];
    });
}

- (void)timerFired:(NSTimer *)timer {
    if (self.timer) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self nextAction];
        });
    }
}

- (void)stopTimer {
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

// 答题状态
-(void)setQuestionState:(QuestionState)questionState {
    _questionState = questionState;
    
    NSLog(@"🔥🔥🔥===================== 状态：%lu",(unsigned long)questionState);

    HSItem *item = [self.dataAry objectAtIndex:self.mainIndex];
    HSQuestion *question = item.questions[self.subIndex];
    HSTemplateSettings *tiganModel = item.templateSettings;
    HSListeningAndSpeakingRule *setting = tiganModel.listeningAndSpeakingRule;

    if (questionState == QuestionStateReady) {
        self.stateView.hidden = YES;
        
        [self startTimerWithTime:1];
    }
    
    if (questionState == QuestionStateTingtigan) {
        
        NSString *url = [NSString stringWithFormat:@"%@%@",self.testModel.resmain,tiganModel.audioUrl];
        [self.player playerWithURL:url];
        NSUInteger time = [self.player getDurationWithUrlString:url];
        self.stateView.hidden = NO;
        [self.stateView setQuestionStyle:1 time:time+1];
        [self startTimerWithTime:time+1];
    }
    
    if (questionState == QuestionStateYueti) {
        self.stateView.hidden = NO;
        [self.stateView setQuestionStyle:2 time:setting.lookTime+1];
        
        [self startTimerWithTime:setting.lookTime+1];
    }
    
    if (questionState == QuestionStateDuNeirong) {

        HSTrunk *trunk = question.trunk;
        HSValueAttachment *Attachment = question.type==1 ? trunk.attachments.firstObject : trunk.attachments.lastObject;
        NSString *url = [NSString stringWithFormat:@"%@%@",self.testModel.resmain,Attachment.url];
        [self.player playerWithURL:url];
        NSUInteger time = [self.player getDurationWithUrlString:url];
        self.stateView.hidden = NO;
        [self.stateView setQuestionStyle:1 time:time+1];
        [self startTimerWithTime:time+1];
    }
    
    if (questionState == QuestionStateStartDati) {
        
        self.stateView.hidden = NO;
        [self.stateView setQuestionStyle:3 time:setting.answerTime];

        [self startTimerWithTime:setting.answerTime+1];
    }
    
    if (questionState == QuestionStateEndDati) {
        
        self.stateView.hidden = YES;
        [self nextAction];
    }
    [self.tableView reloadData];

}

// 下一步
- (void)nextAction {
    [self stopTimer];

    HSItem *item = [self.dataAry objectAtIndex:self.mainIndex];
    HSQuestion *question = item.questions[self.subIndex];
    NSLog(@"🔥🔥🔥=====================下一步 状态：%lu main:%lu sub:%lu children:%lu questions:%@  childrens:%@",(unsigned long)self.questionState,(unsigned long)self.mainIndex,(unsigned long)self.subIndex,(unsigned long)self.childrenIndex,item.questions,question.children);

    if (self.questionState == QuestionStateEndDati) {
        if(self.mainIndex == self.dataAry.count-1){
            TingliResultViewController *vc = [[TingliResultViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }else {
            if(self.subIndex == item.questions.count-1){
                if(question.type == 5){
                    if(self.childrenIndex == question.children.count-1){
                        self.mainIndex = self.mainIndex+1;
                        self.subIndex = 0;
                        self.childrenIndex = 0;
                        self.questionState = QuestionStateReady;
                        [self.tableView reloadData];
                    }else {
                        self.childrenIndex = self.childrenIndex+1;
                        self.questionState = QuestionStateYueti;
                        [self.tableView reloadData];
                    }
                }else {
                    self.mainIndex = self.mainIndex+1;
                    self.subIndex = 0;
                    self.childrenIndex = 0;
                    self.questionState = QuestionStateReady;
                    [self.tableView reloadData];
                }
            }else {
                self.subIndex = self.subIndex+1;
                self.childrenIndex = 0;
                self.questionState = QuestionStateYueti;
                [self.tableView reloadData];
            }
        }
    }else {
        
        if(question.type == 5 && self.childrenIndex != 0 && self.questionState == QuestionStateYueti){
            self.questionState = QuestionStateStartDati;
        }else {
            self.questionState = self.questionState+1;
        }
        [self.tableView reloadData];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    HSItem *item = [self.dataAry objectAtIndex:self.mainIndex];
    HSQuestion *question = item.questions.firstObject;
    if (self.questionState == QuestionStateReady || self.questionState == QuestionStateTingtigan) {
        return 1;
    }
    if(question.type == 5){
        HSQuestion *childrenquestion = question.children[self.childrenIndex];
        return 2+childrenquestion.options.count;
    }else {
        return 2+question.options.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) { // 题干
        HearingQuestionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HearingQuestionTableViewCell" forIndexPath:indexPath];
        if (!cell) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"HearingQuestionTableViewCell" owner:self options:nil] lastObject];
        }
        if (self.questionState == QuestionStateReady || self.questionState == QuestionStateTingtigan) {
            cell.titleLB.textColor = rgbHex(0x333333, 1);
        }else {
            cell.titleLB.textColor = rgbHex(0xb5b5b5, 1);
        }
        HSItem *item = [self.dataAry objectAtIndex:self.mainIndex];
        cell.tiganModel = item.templateSettings;
        return cell;
    }
    else if (indexPath.row == 1) { // 问题
        QuestionTurnkCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QuestionTurnkCell" forIndexPath:indexPath];
        if (!cell) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"QuestionTurnkCell" owner:self options:nil] lastObject];
        }
        HSItem *item = [self.dataAry objectAtIndex:self.mainIndex];
        HSQuestion *question = item.questions[self.subIndex];
        
        if(question.type == 5){
            cell.imView.hidden = YES;
            cell.titleTB.hidden = NO;
            HSQuestion *childrenquestion = question.children[self.childrenIndex];
            cell.titleTB.text = childrenquestion.trunk.body;
        }else if(question.type == 3){
            cell.imView.hidden = NO;
            cell.titleTB.hidden = YES;
            HSValueAttachment * attachment = question.trunk.attachments.firstObject;
            [cell.imView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",self.testModel.resmain,attachment.url]]];
        }else {
            cell.imView.hidden = YES;
            cell.titleTB.hidden = NO;
            cell.titleTB.text = question.trunk.body;
        }
        return cell;
    } 
    else { // 选项
        HSItem *item = [self.dataAry objectAtIndex:self.mainIndex];
        HSQuestion *question = item.questions[self.subIndex];
        if(question.type == 3){
            
            QuestionWriteTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QuestionWriteTableViewCell" forIndexPath:indexPath];
            if (!cell) {
                cell = [[[NSBundle mainBundle]loadNibNamed:@"QuestionWriteTableViewCell" owner:self options:nil] lastObject];
            }
            HSQuestionOption *option = question.options[indexPath.row-2];
            cell.titleLB.text = option.sort;
            return cell;
        }
        else {
            HearingOptionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HearingOptionTableViewCell" forIndexPath:indexPath];
            if (!cell) {
                cell = [[[NSBundle mainBundle]loadNibNamed:@"HearingOptionTableViewCell" owner:self options:nil] lastObject];
            }
            if(question.type == 5){
                HSQuestion *childrenquestion = question.children[self.childrenIndex];
                HSQuestionOption *option = childrenquestion.options[indexPath.row-2];
                HSValue *model = option.value.firstObject;
                if(model.body.length){
                    cell.titleLB.text = model.body;
                    cell.imView.hidden = YES;
                }else {
                    cell.imView.hidden = NO;
                    HSValueAttachment * attachment = model.attachments.firstObject;
                    [cell.imView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",self.testModel.resmain,attachment.url]]];
                }
            }else {
                HSQuestionOption *option = question.options[indexPath.row-2];
                HSValue *model = option.value.firstObject;

                cell.numLB.text = [NSString stringWithFormat:@"%ld",(long)(indexPath.row-2)];

                if(model.body.length){
                    cell.titleLB.text = model.body;
                    cell.imView.hidden = YES;
                }else {
                    cell.imView.hidden = NO;
                    HSValueAttachment * attachment = model.attachments.firstObject;
                    [cell.imView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",self.testModel.resmain,attachment.url]]];
                }
            }

            return cell;
        }
        
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < 2) {
        return;
    }
    HSItem *item = [self.dataAry objectAtIndex:self.mainIndex];
    HSQuestion *question = item.questions[self.subIndex];
    HSTemplateSettings *tiganModel = item.templateSettings;
    HSQuestionOption *option = question.options[indexPath.row-2];
    HSValue *model = option.value.firstObject;

    if (question.type==5) {
        question = question.children[self.childrenIndex];
    }
    NSDictionary *param = @{
        @"mission_id":question.moduleId,
        @"question_type":@(question.type),
        @"qtype":@(2),
        @"version_id":question.moduleId,
        @"source_id":question.versionId,
        @"son_source_id":question.versionId,
        @"score":@(100),
        @"wz_score":@(100),
        @"ll_score":@(100),
        @"zq_score":@(100),
        @"answer_remark":@(1),
        @"true_answer_options_id":option.id,
        @"true_answer_body":@"no",
        @"answer_options_id":option.id,
        @"source_url":@"jiade",
        @"full_score":question.sort,
    };
    [self submitAnser:param];
}

- (void)submitAnser:(NSDictionary *)param {
    [HomeRequest submitAnserWith:param result:^(BOOL ret) {
        NSLog(@"===================%d",ret);
    }];
}

- (void)rightBtnAction {
    WS(WeakSelf)
    [ChangeItemView chooseModulenWithQuestions:self.dataAry index:self.mainIndex Complection:^(NSUInteger index) {
        [WeakSelf stopTimer];
        WeakSelf.mainIndex = index;
        WeakSelf.subIndex = 0;
        WeakSelf.childrenIndex = 0;
        WeakSelf.questionState = QuestionStateReady;
        [WeakSelf.tableView reloadData];
    }];

}

- (void)back {
    [self.player pause];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

#pragma mark - PlayManagerDelegate
- (void)musicFinsh {
    NSLog(@"🔥🔥🔥===================== 播放完成：%lu",(unsigned long)self.questionState);

}

- (void)playStateChange:(AVPlayerItemStatus)state {

}

@end
